<?php
namespace Mouta\AmistateBundle\Form\Handler;

use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\Container;
use FOS\UserBundle\Model\UserManagerInterface;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Mailer\MailerInterface;
use FOS\UserBundle\Form\Handler\RegistrationFormHandler as BaseRegistrationFormHandler;
use Mouta\AmistateBundle\Entity\ImagenUsuario;

class RegistrationFormHandler extends BaseRegistrationFormHandler
{
    protected $mailer;
    
    public function __construct(Form $form, Request $request, UserManagerInterface $userManager,MailerInterface $mailer)
    {
        $this->form = $form;
        $this->request = $request;
        $this->userManager = $userManager;
        $this->mailer = $mailer;
    }
    
    public function process($confirmation = false)
    {
        $user = $this->userManager->createUser();
        $this->form->setData($user);
        
        if ('POST' == $this->request->getMethod()) {
            $this->form->bindRequest($this->request);
            if ($this->form->isValid()) {
                $this->onSuccess($user, $confirmation);
                $now = date_create_from_format('d/m/Y', date('d/m/Y'));
                $ui = new ImagenUsuario();
                $ui->setUsuario($user);
                $ui->setCreatedAt($now);
                $ui->setDefa(1);
                $uploaded = $ui->uploadImagen($this->request);
                if($uploaded)
                {
                    $this->userManager->saveImage($ui);
                }
                return true;
            }
        }
        $this->form->setData($user);
        return false;
    }
}
